import {onMounted, onUnmounted, ref} from "vue";
import {useStore} from "vuex";
// 当前窗口宽度小于992时，侧边栏折叠
const WIDTH = 1024
// 当窗口小于720时关闭侧边栏
const CloseWidth = 720

const useWindowSize = () => {
    const isClient = typeof window === 'object'
    const sizeFlag = ref(false)
    const store = useStore()
    // 获取当前窗口宽度
    const getSize = () => {
        return isClient ? window.innerWidth : undefined
    }

    // 监听窗口大小变化
    const onResize = () => {
        // 存储当前宽度
        store.commit('action/setWidth', getSize())
        //  当前窗口宽度小于992时，侧边栏折叠
        store.commit('action/setCollapse', getSize() < WIDTH)
        // 当窗口小于720时关闭侧边栏
        store.commit('action/setCloseCollapse', getSize() > CloseWidth)
        if (store.getters.sidebar.drawerOpen && store.getters.sidebar.closeCollapse) {
            store.commit('action/setDrawerOpen', false)
        }
    }

    // 监听窗口大小变化
    onResize()

    onMounted(() => {
        // 监听窗口大小变化
        window.addEventListener('resize', onResize)
    })

    onUnmounted(() => {
        //  移除监听窗口大小变化
        window.removeEventListener('resize', onResize)
    })
    return sizeFlag
}

export default useWindowSize
